// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const domainName = "http://127.0.0.1:8090/api/"
const wsAddress = "ws://127.0.0.1:8090/websocket/"
//const domainName = "http://47.113.89.104:8090/api/"
//const wsAddress = "ws://47.113.89.104:8090/websocket/"
cc.Class({
    extends: cc.Component,

    properties: {
        cardPrefab: {
            default: null,
            type: cc.Prefab,
        },
        cardBack : {
            default : null,
            type : cc.Prefab,
        },
        clock : {
            default : null,
            type : cc.Prefab,
        },
        text : {
            default : null,
            type : cc.Prefab,
        },
        avatar : {
            default : null,
            type : cc.Prefab,
        },
        lordCard : {
            default : null,
            type : cc.Prefab,
        },
        huanledou : {
            default : null,
            type : cc.Prefab,
        },
        initCards : {
            default: [],
            visible : false
        },
        choosedCard : {
            default : [],
            visible : false,
        }
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},


    // 网络链接成功了之后调用
    on_open: function (event) {
        // test
        this.send_data("HelloWorld");
        // end
    },

    // 客户端收到数据的时候
    on_message: function (event) {
        console.log("#####", event.data);
        var data = JSON.parse(event.data);
        console.log(data.msgType);
        if (data.msgType == "InitialPosition") {
            this.node.getChildByName('grabLordBtns').active = false;
            this.lordPos = data.playerPosition;
            this.status = 1;   //是否显示文字
            this.showTextType = 1;  //显示按钮文字
            this.showTextType2 = 1; //显示文字
            this.showGrabLord();
            this.showClock(this.lordPos, 1);
            //console.log(this.lordPos);
        }
        else if (data.msgType == "RobTheLord") {
            this.status = 2;
            if (data.nowPosition == this.playerId) {
                this.node.getChildByName('grabLordBtns').active = false;
            }
            this.lordPos = data.nextPosition;
            this.preGrabLord = { pos: data.nowPosition, grab: data.robFlag };
            if(this.preGrabLord.grab == true) {
                this.showTextType = 2;    //按钮的文字
            }
            this.showGrabLord();
            if (this.preGrabLord.grab == true) {
                this.showTextType2 = 2;      //显示的文字
            }
            this.showClock(this.lordPos, 1);
            
        }
        else if (data.msgType == "FinalLord") {
            this.textNode.destroyAllChildren();
            this.textNode.removeAllChildren();
            this.node.getChildByName("grabLordBtns").active = false;
            this.lordPlayer = data.finalLordPosition;
            this.lordPos = data.finalLordPosition;
            this.showLordAvatar(this.lordPlayer);
            this.showLordCard();
            this.showActionBtn();
            this.judgeCard(); //更新可出牌状态；
            this.refreshNumber(data.finalLordPosition, 3);   //更新牌数
            this.showClock(this.lordPos, 2);
            
        }
        else if (data.msgType == "PlayCard") {
            this.lordPos = data.nextPosition;
            this.prePos = data.nowPosition;
            var pos = this.getPosById(data.nowPosition);
            if(pos != 0) {
                var outCard = pos == -1 ? this.node.getChildByName('outCard1') : this.node.getChildByName('outCard2');
                outCard.destroyAllChildren();
                outCard.removeAllChildren();
            }
            this.textNode.destroyAllChildren();
            this.textNode.removeAllChildren();
            if (data.playFlag) {   //有人出牌
                if (pos != 0) {
                    this.playCardNum = data.playCardList.length;
                    for (var i in data.playCardList.reverse()) {
                        this.generateCard(data.playCardList[i].decor, data.playCardList[i].cardFace, data.playCardList[i].value, i, pos == -1 ? 3 : 4);
                    }
                    this.refreshNumber(data.nowPosition, -data.playCardList.length);
                }
                this.playSound(3, this.cardTypeToSoundValue(data.cardType.cardTypeEnum, data.cardType.value));
            }
            else {
                var text = cc.instantiate(this.text);
                var relaPos = this.getPosById(data.nowPosition);
                var textPos = relaPos == 0 ? new cc.v2(0, -80) : relaPos == -1 ? new cc.v2(-220, 0) : new cc.v2(220, 0);
                text.setPosition(textPos);
                this.textNode.addChild(text, "notPlay");
                text.getComponent(cc.Label).string = "不要";
                this.playSound(2, 0);

            }
            if(this.lordPos == this.playerId) {
                this.showActionBtn();
                this.node.getChildByName("outCard").destroyAllChildren();
            }
            this.showClock(this.lordPos, 2);
            this.judgeCard();
            
        }
        else if(data.msgType == "Result") {
            this.hideClock();
            if(data.winner == "landlord") {
                if(data.winnerPosition == this.playerId) {
                    this.gameOver(2);
                }
                else {
                    this.gameOver(3);
                }
            }
            else {
                if(this.lordPlayer != this.playerId) {
                    this.gameOver(1);
                }
                else {
                    this.gameOver(4);
                }
            }
        }
        else if (data.msgType == "Restart") {
            this.regrabLord();
        }
        else if (data.msgType == "EnterRoomInf") {
            this.positionFlag = data.positionFlag;
            this.prepareFlag = data.prepareFlag;
            this.beanInfo = data.userBeans;
            this.usernameList = data.usernameList;
            this.updataInfo();
            this.updataPreInfo();
            this.updataBeanNumber();

        }
        else if (data.msgType == "PrepareInf") {
            if(data.prepareFlag[1] && data.prepareFlag[2] && data.prepareFlag[3]) {
                this.prepareText.active = false;
                this.node.getChildByName("prepareMenu").active = false;
                this.startPlayer();
            }
            this.positionFlag = data.positionFlag;
            this.prepareFlag = data.prepareFlag;
            this.updataPreInfo();
        }
        else if (data.msgType == "LeaveRoomInf") {
                this.positionFlag = data.positionFlag;
                this.prepareFlag = data.prepareFlag;
                this.updataInfo();
                this.updataPreInfo();
                this.resetAvatar();
            
            if(this.isPlaying){
                this.isPlaying = false;
                this.restart();
            }
        }
        else if (data.msgType == "init") {
            this.positionFlag = data.positionFlag;
            this.prepareFlag = data.prepareFlag;
            this.updataInfo();
            this.updataPreInfo();
        }
        else if(data.msgType == "BeansChange") {
            this.beanInfo = data.userBeans;
            this.updataBeanNumber();
        }

    },

    // 客户端收到socket 关闭的时间的时候调用;
    on_close: function (event) {
        this.close();
    },

    on_error: function (event) {
        this.close();
    },

    close: function () {
        if (this.sock != null) {
            this.sock.close(); // 关闭socket
            this.sock = null;
        }
    },

    // 链接函数, 
    connect: function () {
        var url = wsAddress + this.roomId + "/" + this.playerId;
        this.sock = new WebSocket(url); // h5标准的websocket对象
        this.sock.binaryType = "arraybuffer"; // 配置接受二进制的数据类型,与服务器保持一次, "Blob"

        // 为这个websocket对象制定对应的回掉函数;
        this.sock.onopen = this.on_open.bind(this);
        this.sock.onmessage = this.on_message.bind(this);
        this.sock.onclose = this.on_close.bind(this);
        this.sock.onerror = this.on_error.bind(this);
    },

    // 发送数据, sock.send;
    send_data: function (data) {
        this.sock.send(data);
    },


    start () {
        this.roomId = 0;
        this.node.getChildByName('grabLordBtns').active = false;
        this.node.getChildByName("beginMenu").active = true;
        this.hideActionBtn();
        this.node.getChildByName('endMenu').active = false;
        this.node.getChildByName('endMenu').zIndex = 16;
        
        
    },

    startGame : function() {
        console.log(this.roomId);
        if(isNaN(this.roomId) || this.roomId == undefined ) {
            return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open("POST", domainName+ "game/room");
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("token", this.token);
        var that = this;
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                console.log(xhr.response);
                if (JSON.parse(xhr.response).code == 0) {
                    that.playerId = JSON.parse(xhr.response).data.playerPosition;
                    that.showPlayerInfo();
                    that.showLordAvatar();
                    that.showPrepareText();
                    that.node.getChildByName("beginMenu").active = false;
                    that.node.getChildByName("prepareMenu").active = true;
                    that.node.getChildByName("roomType").getChildByName("text").getComponent(cc.Label).string = that.getTypeString(JSON.parse(xhr.response).data.roomLevel);
                    that.connect();
                }
            }
        }
        var data = {
            roomId: this.roomId,
        };
        xhr.send(JSON.stringify(data));
    },

    getTypeString : function(type) {
        switch (type) {
            case "ROOM_NOVICE":
                return "新手场";
            case "ROOM_PRIMARY":
                return "初级场";
            case "ROOM_INTERMEDIATE":
                return "中级场";
            case "ROOM_ADVANCED":
                return "高级场";
            case "ROOM_MASTER":
                return "大师场";
            case "ROOM_KING":
                return "开炮场";
            default:
                return "不知道什么场";
        }
    },

    inputRoomId: function (text, editbox) {
        console.log(parseInt(text));
        console.log(editbox);
        this.roomId = parseInt(text);
    },

    showGrabLord :function() {
        if(this.lordPos == this.playerId) {
            if(this.showTextType == 1) {   // 
                this.node.getChildByName('grabLordBtns').active = true;
                cc.find("Canvas/grabLordBtns/grab/Background/Label").getComponent(cc.Label).string = "叫地主";
                cc.find("Canvas/grabLordBtns/notgrab/Background/Label").getComponent(cc.Label).string = "不叫";

            }
            else if(this.showTextType == 2) { //
                this.node.getChildByName('grabLordBtns').active = true;
                cc.find("Canvas/grabLordBtns/grab/Background/Label").getComponent(cc.Label).string = "抢地主";
                cc.find("Canvas/grabLordBtns/notgrab/Background/Label").getComponent(cc.Label).string = "不抢";

            }
            
        }
        if(this.status == 2) {
            var text = cc.instantiate(this.text);
            var relaPos = this.getPosById(this.preGrabLord.pos)
            var textPos = relaPos == 0 ? new cc.v2(0, -80) : relaPos == -1 ?  new cc.v2(-220, 0) : new cc.v2(220, 0);
            text.setPosition(textPos);
            this.textNode.addChild(text);
            console.log("add");
            if(this.showTextType2 == 1) {
                text.getComponent(cc.Label).string = this.preGrabLord.grab ? "叫地主" : "不叫";
                this.playSound(1, this.preGrabLord.grab ? 1 : 2);
            }
            else {
                text.getComponent(cc.Label).string = this.preGrabLord.grab ? "抢地主" : "不抢";
                this.playSound(1, this.preGrabLord.grab ? 3 : 4);
            }
        }

    },

    prepare : function() {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", domainName + "game/preparation");
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("token", this.token);
        var that = this;
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                that.node.getChildByName("prepareMenu").active = false;
                console.log(xhr.response);
            }
        }
        var data = {
            roomId: this.roomId,
            playerPosition : this.playerId,
        };
        xhr.send(JSON.stringify(data));
    },

    getPosById : function(id) {
        if(id == this.playerId) {
            return 0;
        }
        else if(id == this.playerId + 1) {
            return 1;
        }
        else if(id == this.playerId - 1) {
            return -1;
        }
        else if(id == this.playerId + 2) {
            return -1;
        }
        else if(id == this.playerId - 2) {
            return 1;
        }
        return 0;
    },
    gradLord : function() {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", domainName + "lord/rob", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("token", this.token);
        var that = this;
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                console.log(JSON.parse(xhr.response));
            }
        }
        var data = {
            roomId: this.roomId,
        };
        xhr.send(JSON.stringify(data));
    },

    unGradLord : function() {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", domainName + "lord/not", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("token", this.token);
        var that = this;
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                console.log(JSON.parse(xhr.response));
            }
        }
        var data = {
            roomId: this.roomId,
        };
        xhr.send(JSON.stringify(data));
    },

    startPlayer : function() {
        this.isPlaying = true;
        this.initCard();
        this.playSound(0, 1);
    },

    generateCard(decor, cardFace, value, index, type) {
        const faces = ["", "A", "2", "3", "4", "5", "6", "7", "8", "9", "=", "J", "Q", "K", "J\nO\nK\nE\nR", "J\nO\nK\nE\nR"];
        var card;
        if(index >= 0 && type == 1) {
            card = cc.instantiate(this.cardPrefab);
            card.getComponent('card').game = this;
            card.getComponent('card').id = index;
            card.getComponent('card').decor = decor;
            card.getComponent('card').cardFace = cardFace;
            card.getComponent('card').value = value;
            card.getComponent('card').width = this.node.width;
            this.node.getChildByName("cards").addChild(card);
            this.cardValues.push(value);
            
        }
        else if(type == 2) {
            card = cc.instantiate(this.lordCard);
            this.node.getChildByName("outCard").addChild(card);
        }
        else if(type == 3) {
            card = cc.instantiate(this.lordCard);
            this.node.getChildByName("outCard1").addChild(card);
        }
        else if(type == 4) {
            card = cc.instantiate(this.lordCard);
            this.node.getChildByName("outCard2").addChild(card);
        }
        else {
            card = cc.instantiate(this.lordCard);
            this.node.getChildByName("lordCards").addChild(card);
        }
        var m_decor = decor == 1 ? "{" : decor == 2 ? "[" : decor == 3 ? "}" : decor == 4 ? "]" : "}";
        var m_cardFace = faces[cardFace];
        var m_cardColor = decor == 0 ? (value == 14 ? new cc.color(0, 0, 0, 255) : new cc.color(255, 72, 72, 255)) : decor <= 2 ? new cc.color(255, 72, 72, 255) : new cc.color(0, 0, 0, 255);
        card.getChildByName('faces').getComponent(cc.Label).string = m_cardFace;
        card.getChildByName('faces').color =  m_cardColor;
        if(decor > 0) {
            card.getChildByName('color').getComponent(cc.Label).string = m_decor;
            card.getChildByName('color').color = m_cardColor;            
        }
        else {
            card.getChildByName('faces').getComponent(cc.Label).fontSize = 25;
            card.getChildByName('faces').getComponent(cc.Label).lineHeight = 25;
            card.getChildByName('faces').setPosition(-45, 15);
            card.removeChild(card.getChildByName('color'));
        }
        card.setPosition(this.getCardPosition(index, type));
        return card;
    },

    getCardPosition(index, type) {
        if(type == 1) {
            if (index >= 0) {
                var left = this.cardNum * -22.5 + 30;
                return cc.v2(left + 45 * index, -210);
            }
            else {
                return cc.v2(45 + 22.5 * index, 270);
            }
        }
        else if(type == 2) {
            var left = this.playCardNum * -22.5 / 2 + 10;
            return cc.v2(left + 22.5 * index, -40);
        }
        else if(type == 3) {
            return cc.v2(-225 + 22.5*index, 0);
        }
        else if(type == 4) {
            var left = 250-22.5*this.playCardNum;
            return cc.v2(left+22.5*index, 0);
        }

    },

    onLoad() {
        this.node.addChild(new cc.Node(), 1, "cards");
        this.node.addChild(new cc.Node(), 1, "lordCards");
        this.node.addChild(new cc.Node(), 1, 'outCard');
        this.node.addChild(new cc.Node(), 1, 'outCard1');
        this.node.addChild(new cc.Node(), 1, 'outCard2');
        this.node.addChild(new cc.Node(), 1, "cardBack");
        this.textNode = new cc.Node();
        this.node.addChild(this.textNode, 1, "textNode");
        this.isJudge = false;
        this.clockLabel = this.node.getChildByName("clock").getChildByName("time").getComponent(cc.Label);
        this.node.getChildByName("clock").active = false;
        this.node.getChildByName("prepareMenu").active = false;
        this.node.getChildByName("register").active = false;
        this.node.getChildByName("beginMenu").active = false;
        this.node.getChildByName("login").active = true;
        this.isPlaying = false;
        this.cardValues = [];
    },

    onDestroy() {
        this.send_data("byebye");
        this.close();
    },

    initCard() {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", domainName + "card/farmer", true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("token", this.token);
        var that = this;
        this.cardInstance = [];
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4) {
                console.log(JSON.parse(xhr.response).data.initialCards);
                that.initCards = JSON.parse(xhr.response).data.initialCards;
                that.cardNum = that.initCards.length;
                for (var i in that.initCards.reverse()) {
                    that.cardInstance.push(that.generateCard(that.initCards[i].decor, that.initCards[i].cardFace, that.initCards[i].value, i, 1));
                }
                
            }
        }
        var data = {
            roomId : this.roomId,
            playerPosition : this.playerId,
        };
        xhr.send(JSON.stringify(data));
        if(this.playerId == 1) {
            var xhr2 = new XMLHttpRequest();
            xhr2.open("POST", domainName + 'lord/init', true);
            xhr2.setRequestHeader("Content-Type", "application/json");
            xhr2.setRequestHeader("token", this.token);
            xhr2.withCredentials = true;
            xhr2.onreadystatechange = function () {
                if (xhr.readyState == 4) {

                }
            }
            var data = {
                roomId: this.roomId
            };
            xhr2.send(JSON.stringify(data));
        }
        var cardLeft = cc.instantiate(this.cardBack);
        var cardRight = cc.instantiate(this.cardBack);
        cardLeft.setPosition(-300, 0);
        cardLeft.getChildByName("cardNum").getComponent(cc.Label).string = 17;
        cardRight.setPosition(300, 0);
        cardRight.getChildByName('cardNum').getComponent(cc.Label).string = 17;
        this.node.getChildByName("cardBack").addChild(cardLeft);
        this.node.getChildByName("cardBack").addChild(cardRight);
        this.leftCardNum = 17;
        this.rightCardNum = 17;
        this.leftCard = cardLeft.getChildByName("cardNum");   //便于修改牌数
        this.rightCard = cardRight.getChildByName('cardNum');
        
    },
    updataInfo : function() {    //更新头像和昵称
        this.infoNode.getChildByName("player1").getComponent(cc.Label).string = this.usernameList[1];
        this.infoNode.getChildByName('player1').active = this.positionFlag[1] ? true : false;
        this.infoNode.getChildByName("player2").getComponent(cc.Label).string = this.usernameList[2];
        this.infoNode.getChildByName('player2').active = this.positionFlag[2] ? true : false;
        this.infoNode.getChildByName("player3").getComponent(cc.Label).string = this.usernameList[3];
        this.infoNode.getChildByName('player3').active = this.positionFlag[3] ? true : false;
        this.avatarNode.getChildByName('player1').active = this.positionFlag[1] ? true : false;
        this.avatarNode.getChildByName('player2').active = this.positionFlag[2] ? true : false;
        this.avatarNode.getChildByName('player3').active = this.positionFlag[3] ? true : false;
        
    },

    updataBeanNumber : function() {
        for(var i = 1; i <= this.beanNode.children.length; i++) {
            this.beanNode.children[i-1].getChildByName("number").getComponent(cc.Label).string = this.beanInfo[i];
            this.beanNode.children[i-1].active = this.positionFlag[i] ? true : false;
        }

    },

    showPlayerInfo : function() {  //在相应位置显示玩家昵称
        this.infoNode = new cc.Node("infoNode");
        this.node.addChild(this.infoNode);
        this.beanNode = new cc.Node("beanNode");
        this.node.addChild(this.beanNode);
        var pos1 = this.getPosById(1);
        var text = cc.instantiate(this.text);
        text.getComponent(cc.Label).string = "玩家一";
        text.setPosition(pos1 == 0 ? new cc.v2(0, -305) : pos1 == -1 ? new cc.v2(-400, 0) : new cc.v2(400, 0));
        this.infoNode.addChild(text, 1, "player1");
        var bean = cc.instantiate(this.huanledou);
        bean.setPosition(pos1 == 0 ? new cc.v2(70, -305) : pos1 == -1 ? new cc.v2(-400, -50) : new cc.v2(400, -50))
        this.beanNode.addChild(bean);
    
        var pos2 = this.getPosById(2);
        var text2 = cc.instantiate(this.text);
        text2.getComponent(cc.Label).string = "玩家二";
        text2.setPosition(pos2 == 0 ? new cc.v2(0, -305) : pos2 == -1 ? new cc.v2(-400, 0) : new cc.v2(400, 0));
        this.infoNode.addChild(text2, 1, "player2");
        var bean2 = cc.instantiate(this.huanledou);
        bean2.setPosition(pos2 == 0 ? new cc.v2(70, -305) : pos2 == -1 ? new cc.v2(-400, -50) : new cc.v2(400, -50))
        this.beanNode.addChild(bean2);

        var pos3 = this.getPosById(3);
        var text3 = cc.instantiate(this.text);
        text3.getComponent(cc.Label).string = "玩家三";
        text3.setPosition(pos3 == 0 ? new cc.v2(0, -305) : pos3 == -1 ? new cc.v2(-400, 0) : new cc.v2(400, 0));
        this.infoNode.addChild(text3, 1 , "player3");
        var bean3 = cc.instantiate(this.huanledou);
        bean3.setPosition(pos3 == 0 ? new cc.v2(50, -305) : pos3 == -1 ? new cc.v2(-400, -50) : new cc.v2(400, -50))
        this.beanNode.addChild(bean3);

        
        for(var i in this.infoNode.children) {
            this.infoNode.children[i].active = false;
        }
        for(var i in this.beanNode.children) {
            this.beanNode.children[i].active = false;
        }


    },

    showLordAvatar : function(lordPos) {   //不传地主位置参数时显示三个农民头像，传地主位置将该位置替换为地主头像
        if(lordPos == undefined) {
            this.avatarNode = new cc.Node("avatarNode");
            this.node.addChild(this.avatarNode);
            var pos1 = this.getPosById(1);
            var avatar1 = cc.instantiate(this.avatar);
            avatar1.setPosition(pos1 == 0 ? new cc.v2(-80, -305) : pos1 == -1 ? new cc.v2(-385, 60) : new cc.v2(385, 60));
            this.avatarNode.addChild(avatar1, 1, "player1");

            var pos2 = this.getPosById(2);
            var avatar2 = cc.instantiate(this.avatar);
            avatar2.setPosition(pos2 == 0 ? new cc.v2(-80, -305) : pos2 == -1 ? new cc.v2(-385, 60) : new cc.v2(385, 60));
            this.avatarNode.addChild(avatar2, 1, "player2");

            var pos3 = this.getPosById(3);
            var avatar3 = cc.instantiate(this.avatar);
            avatar3.setPosition(pos3 == 0 ? new cc.v2(-80, -305) : pos3 == -1 ? new cc.v2(-385, 60) : new cc.v2(385, 60));
            this.avatarNode.addChild(avatar3, 1, "player3");
            for(var i in this.avatarNode.children) {
                this.avatarNode.children[i].active = false;
            }
        }
        else {
            var that = this;
            if(lordPos == 1) {
                cc.resources.load("地主", cc.SpriteFrame, (err, sprite) => {
                    console.log(sprite);
                    that.avatarNode.getChildByName("player1").getComponent(cc.Sprite).spriteFrame = sprite;

                })
            }
            else if(lordPos == 2) {
                cc.resources.load("地主", cc.SpriteFrame, function (err, sprite) {
                    console.log(sprite);
                    that.avatarNode.getChildByName("player2").getComponent(cc.Sprite).spriteFrame = sprite;

                
                })
            }
            else if(lordPos == 3) {
                cc.resources.load("地主", cc.SpriteFrame, function (err, sprite) {
                    console.log(sprite);
                    that.avatarNode.getChildByName("player3").getComponent(cc.Sprite).spriteFrame = sprite;

                })
            }
        }

        
    },

    resetAvatar : function() {
        var that = this;
        if(this.lordPlayer != undefined) {
            cc.resources.load("农民", cc.SpriteFrame, function (err, assert) {
                console.log(that.avatarNode);
                console.log("player" + that.lordPlayer);
                that.avatarNode.getChildByName("player" + that.lordPlayer).getComponent(cc.Sprite).spriteFrame = assert;
            })
        }
    },

    updataPreInfo : function() {    //更新准备信息
        this.prepareText.getChildByName("player1").active = this.prepareFlag[1] ? true : false;
        this.prepareText.getChildByName("player2").active = this.prepareFlag[2] ? true : false;
        this.prepareText.getChildByName("player3").active = this.prepareFlag[3] ? true : false;
    },

    showPrepareText : function() {
        this.prepareText = new cc.Node();
        this.node.addChild(this.prepareText, 1, "prepareText");
        var pos1 = this.getPosById(1);
        var text = cc.instantiate(this.text);
        text.getComponent(cc.Label).string = "已准备";
        text.setPosition(pos1 == 0 ? new cc.v2(0, -100) : pos1 == -1 ? new cc.v2(-280, 0) : new cc.v2(280, 0));
        this.prepareText.addChild(text, 1, "player1");
        var pos2 = this.getPosById(2);
        var text2 = cc.instantiate(this.text);
        text2.getComponent(cc.Label).string = "已准备";
        text2.setPosition(pos2 == 0 ? new cc.v2(0, -100) : pos2 == -1 ? new cc.v2(-280, 0) : new cc.v2(280, 0));
        this.prepareText.addChild(text2, 1, "player2");
        var pos3 = this.getPosById(3);
        var text3 = cc.instantiate(this.text);
        text3.getComponent(cc.Label).string = "已准备";
        text3.setPosition(pos3 == 0 ? new cc.v2(0, -100) : pos3 == -1 ? new cc.v2(-280, 0) : new cc.v2(280, 0));
        this.prepareText.addChild(text3, 1, "player3");
        for(var i in this.prepareText.children) {
            this.prepareText.children[i].active = false;
        }

    },

    showLordCard : function() {  //展示并发放地主牌
        var that = this
        var xhr = new XMLHttpRequest();
        xhr.open("POST", domainName + 'card/lord');
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("token", this.token);
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4) {
                var cards = JSON.parse(xhr.response).data.initialCards;
                if(that.lordPlayer == that.playerId) {
                    that.initCards = that.initCards.concat(cards);
                    that.initCards.sort((a, b) => {
                        return b.value - a.value;
                    })
                    that.node.getChildByName("cards").destroyAllChildren();
                    that.node.getChildByName("cards").removeAllChildren(true);
                    that.cardValues = [];
                    that.cardNum = that.initCards.length;
                    that.cardInstance = [];
                    that.choosedCard = [];
                    for(var i in that.initCards) {
                        that.cardInstance.push(that.generateCard(that.initCards[i].decor, that.initCards[i].cardFace, that.initCards[i].value, i, 1));
                    }

                }

                for(var i in cards) {
                    that.generateCard(cards[i].decor, cards[i].cardFace, cards[i].value, -3 + parseInt(i), 1);
                    this.lordCards = cards;
                }
                console.log(xhr.response);
            }
        }
        var data = {roomId : this.roomId};
        xhr.send(JSON.stringify(data));
    },

    chooseCard : function(index){
        this.choosedCard.push(index);
        this.judgeCard();
    },
    cancelChooseCard : function(index) {
        for(var i in this.choosedCard) {
            if(this.choosedCard[i] == index) {
                this.choosedCard.splice(i, 1);
                break;
            }
        }
        this.judgeCard();
        console.log(this.choosedCard);
    },

    showActionBtn : function() {
        if(this.lordPos == this.playerId) {
            this.node.getChildByName('actionNode').active = true;
            this.isJudge = false;
        }
    },

    hideActionBtn : function() {
        this.node.getChildByName('actionNode').active = false;
    },

    judgeCard : function() {  //判断能否出牌
        var that = this;
        this.isJudge = true;
        var xhr = new XMLHttpRequest();
        xhr.open("POST", domainName + 'game/cards');
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("token", this.token);
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4) {
                if(JSON.parse(xhr.response).code == 0) {
                    that.isJudge = false;
                    that.canPlay = JSON.parse(xhr.response).data.playFlag;
                    that.disCardType = JSON.parse(xhr.response).data.disCardType;
                    console.log(that.canPlay);
                    console.log(xhr.response);
                }
                else {
                    that.judgeCard();
                }
            }
        }
        this.upcomingCards = [];
        for(var i in this.choosedCard) {
            this.upcomingCards.push( this.cardNum - this.choosedCard[i] - 1)
        }
        var data = { upcomingCards : this.upcomingCards, roomId : this.roomId};
        xhr.send(JSON.stringify(data));

    },

    playCard : function() {   //出牌
        if(this.isJudge || !this.canPlay) {
            return;
        }
        this.playCardNum = this.upcomingCards.length;
        var that = this;
        var xhr = new XMLHttpRequest();
        xhr.open("POST", domainName + 'game/play');
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("token", this.token);
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4) {
                console.log(xhr.response);
                if(JSON.parse(xhr.response).code == 0) {
                    var outCard = that.node.getChildByName('outCard');
                    outCard.destroyAllChildren();
                    that.cardNum = that.cardNum - that.playCardNum;
                    that.choosedCard.sort((a, b) => { return a - b; });
                    for (var i in that.choosedCard) {
                        var card = that.initCards[that.choosedCard[i]]
                        that.generateCard(card.decor, card.cardFace, card.value, i, 2);
                    }
                    for (var i in that.choosedCard.reverse()) {
                        that.initCards.splice(that.choosedCard[i], 1);
                        that.cardValues.splice(that.choosedCard[i], 1);
                        that.cardInstance[that.choosedCard[i]].destroy();
                        that.cardInstance.splice(that.choosedCard[i], 1);
                    }

                    for (var i in that.cardInstance) {
                        that.cardInstance[i].setPosition(that.getCardPosition(i, 1));
                        that.cardInstance[i].getComponent('card').setId(i);
                    }
                    that.choosedCard = [];
                    that.upcomingCards = [];
                    that.hideActionBtn();
                }           
            }
        }
        var data = { upcomingCards: this.upcomingCards, roomId: this.roomId}
        xhr.send(JSON.stringify(data));


    },

    notPlayCard : function() {  //不出牌
        if (this.disCardType.cardTypeEnum == "CARD_ARBITRARY") {
            return;
        }
        var xhr = new XMLHttpRequest();
        var that = this;
        xhr.open("POST", domainName + 'game/not');
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("token", this.token);
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4) {
                console.log(xhr.response);
                that.hideActionBtn();
            }
        }
        var data = {roomId : this.roomId};
        xhr.send(JSON.stringify(data));
        that.node.getChildByName("outCard").destroyAllChildren();
        for(var i in this.node.getChildByName("cards").children) {
            this.node.getChildByName("cards").children[i].getComponent("card").notChoose();
        }

    },

    defaultPlay : function() {   //必须出牌状态下时间到了默认出牌
        this.canPlay = true;
        var cards = this.node.getChildByName("cards").children;
        for(var i in cards) {
            cards[i].getComponent("card").notChoose2();
        }
        this.choosedCard = [];
        this.upcomingCards = [];
        this.cardValues.sort((a,b)=>{return a-b;});
        var value = this.cardValues[0];
        var num = 0;
        for(var i = 0; i < this.cardValues.length; i++) {
            console.log(value);
            if(this.cardValues[i] == value) {
                this.upcomingCards.push(i);
                this.choosedCard.push(this.cardNum-1-i);
                num++;
                if(num == 4 && i < this.cardValues.length - 1) {
                    num = 0;
                    this.upcomingCards = [];
                    this.choosedCard = [];
                    value = this.cardValues[i+1];
                }
            }
            else if(this.cardValues[i] == 15 && this.cardValues[i-1] == 14) {
                this.upcomingCards.push(i);
                this.choosedCard.push(this.cardNum - 1 - i);
            }
            else {
                break;
            }
        }
        this.cardValues.sort((a, b)=>{return b - a;});
        this.playCard();

    },

    refreshNumber : function(id, cardNum) {
        var pos = this.getPosById(id);
        if(pos == -1) {
            this.leftCardNum += cardNum;
            this.leftCard.getComponent(cc.Label).string = this.leftCardNum;
        }
        else if(pos == 1) {
            this.rightCardNum += cardNum;
            this.rightCard.getComponent(cc.Label).string = this.rightCardNum;
        }
    },

    gameOver : function(imageType) {
        this.lordPos = -1;
        this.hideActionBtn();
        this.node.getChildByName('endMenu').active = true;
        var that = this;
        var imagePath = imageType == 1 ? "农民胜" : imageType == 2 ? "地主胜" : imageType == 3 ? "农民负" : "地主负";
        cc.resources.load(imagePath, cc.SpriteFrame, (err, asset)=>{
            that.node.getChildByName('endMenu').getChildByName('image').getComponent(cc.Sprite).spriteFrame = asset;
        })
        this.node.getChildByName("outCard").destroyAllChildren();
        this.playSound(0, imageType <= 2 ? 3 : 2);

        
        
    },
    restart : function() {    //回到准备状态；
        this.node.getChildByName('grabLordBtns').active = false;
        this.hideActionBtn();
        this.node.getChildByName('endMenu').active = false;
        this.node.getChildByName('beginMenu').active = false;
        this.node.getChildByName("grabLordBtns").active = false;
        this.node.getChildByName("cards").destroyAllChildren();
        this.cardValues = [];
        this.node.getChildByName("outCard").destroyAllChildren();
        this.node.getChildByName("outCard1").destroyAllChildren();
        this.node.getChildByName("outCard2").destroyAllChildren();
        this.node.getChildByName("lordCards").destroyAllChildren();
        this.node.getChildByName("textNode").destroyAllChildren();
        this.node.getChildByName('cardBack').destroyAllChildren();
        this.hideClock();
        this.updataPreInfo();
        this.updataInfo();
        this.resetAvatar();
        this.node.getChildByName("prepareMenu").active = true;
        this.node.getChildByName("prepareText").active = true;
        this.isPlaying = false;
        console.log(this.textNode.children);
               
    },


    regrabLord : function() {   //三个人不叫地主
        this.hideClock();
        this.startPlayer();
        this.textNode.destroyAllChildren();
        this.node.getChildByName("cards").destroyAllChildren();
        this.cardValues = [];
    },

    initafterEnd : function() {   //重置后端
        console.log("~~~重置后端~~~");
        var xhr = new XMLHttpRequest();
        xhr.open("POST", domainName + "game/init");
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader("token", this.token);
        var that = this;
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                console.log(JSON.parse(xhr.response));
            }
        }
        var data = {
            roomId: this.roomId,
        };
        xhr.send(JSON.stringify(data));
    },

    showClock : function(id, type) {
        console.log("addClock");
        if(this.node.getChildByName("clock").active == false) {
            this.node.getChildByName("clock").active = true;
        }
        if (this.clockId != undefined) {
            clearInterval(this.clockId);
        }
        var relaPos = this.getPosById(id);
        var pos = relaPos == 0 ? new cc.v2(0, -70) : relaPos == -1 ? new cc.v2(-220, 70) : new cc.v2(220, 70);
        this.node.getChildByName("clock").setPosition(pos);
        this.clockLabel.string = 0;
        var that = this;
        this.clockId = setInterval(()=>{
            var time = parseInt(this.clockLabel.string) - 1;
            if(time >= 0) {
                that.clockLabel.string = time; 
            }
            else {
                clearInterval(this.clockId);
                if(id == that.playerId && type == 1) {
                    that.unGradLord();
                }
                if(id == that.playerId && type == 2) {
                    if (that.disCardType.cardTypeEnum == "CARD_ARBITRARY") {
                        console.log("default");
                        that.defaultPlay();
                    }
                    else {
                        console.log("notPlay");
                        that.notPlayCard();
                    }
                }
            }
        },1000);

    },
    hideClock : function(id) {
        if(this.clockId != undefined) {
            clearInterval(this.clockId);
        }
        this.node.getChildByName("clock").active = false;
        
    },

    playSound : function(type, value) {
        var resourcePath = null;
        var that = this;
        if(type == 0) {
            if(this.audioId != undefined) {
                cc.audioEngine.stop(this.audioId);
            }
            switch(value) {
                case 0 : resourcePath = "music/MusicEx_Welcome"; break;
                case 1: resourcePath = "music/MusicEx_Exciting";break;
                case 2 :  resourcePath = "music/MusicEx_Lose";break;
                case 3 :  resourcePath = "music/MusicEx_Win";break;
            }
        }
        else if(type == 1) {    //叫地主环节
            switch(value) {
                case 1 : resourcePath = "music/Man_Order"; break;
                case 2 : resourcePath = "music/Man_NoOrder"; break;
                case 3 : var t = Math.floor(Math.random() * 3);
                         resourcePath = t == 0 ? "music/Man_Rob1" : t == 1 ? "music/Man_Rob2" : "music/Man_Rob3"; break;
                case 4 : resourcePath = "music/Man_NoRob"; break;
            }
        }
        else if(type == 2) { //不要
            var t = Math.floor(Math.random() * 4);
            resourcePath = t == 0 ? "music/Man_buyao1" : t == 1 ? "music/Man_buyao2" : t == 2 ? "music/Man_buyao3" : "music/Man_buyao4";
        }
        else if(type == 3) {
            if(value > 100 && value <= 113) {
                resourcePath = "music/Man_" + (parseInt(value)-100);
            }
            else if(value >= 114 && value <= 115) {
                resourcePath = "music/Man_" + (parseInt(value) - 113);
            }
            else if(value >= 116 && value <= 117) {
                resourcePath = "music/Man_" + (parseInt(value) - 102);
            }
            else if(value >= 200 && value <= 213) {
                resourcePath = "music/Man_dui" + (parseInt(value) - 200);
            }
            else if (value >= 214 && value <= 215) {
                resourcePath = "music/Man_dui" + (parseInt(value) - 213);
            }
            else if (value >= 300 && value <= 313) {
                resourcePath = "music/Man_tuple" + (parseInt(value) - 300);
            }
            else if (value >= 314 && value <= 315) {
                resourcePath = "music/Man_tuple" + (parseInt(value) - 313);
            }
            else if(value == 400) {
                resourcePath = "music/Man_sandaiyi";
            }
            else if(value == 401) {
                resourcePath = "music/Man_sandaiyidui";
            }
            else if(value == 403) {
                resourcePath = "music/Man_zhadan";
            }
            else if(value == 404) {
                resourcePath = "music/Man_sidaier";
            }
            else if(value == 405) {
                resourcePath = "music/Man_sidailiangdui";
            }
            else if(value == 406) {
                resourcePath = "music/Man_wangzha";
            }
            else if(value == 407) {
                resourcePath = "music/Man_shunzi";
            }
            else if(value == 408) {
                resourcePath = "music/Man_liandui";
            }
            else if(value == 409) {
                resourcePath = "music/Man_feiji";
            }
            else {
                var t = Math.floor(Math.random() * 3)
                resourcePath = t == 0 ? "music/Man_dani1" : t == 1 ? "music/Man_dani2" : "music/Man_dani3";
            }
        }
        if(resourcePath != null) {
            console.log(resourcePath);
            cc.resources.load(resourcePath, cc.AudioClip, (err, asset) => {
                console.log(asset);
                if(type == 0) {
                    that.audioId = cc.audioEngine.play(asset, true, 1);
                }
                else {
                    cc.audioEngine.play(asset, false, 1);
                }
               
            })
        }
    },

    cardTypeToSoundValue : function(cardTypeEnum, value) {
        if(cardTypeEnum == "CARD_A") {
            return 102 + parseInt(value);
        }
        else if(cardTypeEnum == "CARD_AA") {
            return 202 + parseInt(value);
        }
        else if(cardTypeEnum == "CARD_AAA") {
            return 302 + parseInt(value);
        }
        else if(cardTypeEnum == "CARD_AAAB") {
            return 400;
        }
        else if(cardTypeEnum == "CARD_AAABB") {
            return 401;
        }
        else if(cardTypeEnum == "CARD_AAAA") {
            return 403;
        }
        else if(cardTypeEnum == "CARD_AAAABC") {
            return 404;
        }
        else if(cardTypeEnum == "CARD_AAAABBCC") {
            return 405;
        }
        else if(cardTypeEnum == "CARD_WZ") {
            return 406;
        }
        else if(cardTypeEnum == "CARD_ABCDE") {
            return 407;
        }
        else if(cardTypeEnum == "CARD_AABBCC"){
            return 408;
        }
        else if (cardTypeEnum == "CARD_AAABBBCD" || cardTypeEnum == "CARD_AAABBBCCDD" || cardTypeEnum == "CARD_AAABBB") {
            return 409;
        }
        else {
            return 500;
        }
        
    },
    // update (dt) {},

    hint : function() {
        var a1 = new Array(16).fill(0);     //牌数统计
        var a2 = new Array(16).fill(-1);    //前置同样牌位置
        var a3 = new Array(5).fill(-1);     //某牌数前一牌位置
        var hintCards = [];
        for(var i in this.cardValues) {
            a1[this.cardValues[i]]++;
        }
        for(var i = 15; i > 0; i--) {
            var num = a1[i];
            a2[i] = a3[num];
            a3[num] = i;
        }
        console.log("hint !!!!");
        var cardTypeEnum = this.disCardType.cardTypeEnum;
        var cardValue = this.disCardType.value;
        var cardLength = this.disCardType.length;
        var value;
        if (cardTypeEnum == "CARD_A") {
            value = a3[1];
            while(value != -1 && value <= cardValue) {
                value = a2[value];
            }
            if(value == -1) {
                value = a3[2];
                while(value != -1 && value <= cardValue) {
                    value = a2[value];
                }
                if(value == -1) {
                    value = a3[3];
                    while(value != -1 && value <= cardValue) {
                        value = a2[value];
                    }
                }
            }
            if(value != -1) {
                hintCards.push(value);
            }
           
        }
        else if (cardTypeEnum == "CARD_AA") {
            value = a3[2];
            while (value != -1 && value <= cardValue) {
                value = a2[value];
            }
            if (value == -1) {
                value = a3[3];
                while (value != -1 && value <= cardValue) {
                    value = a2[value];
                }
            }
            if (value != -1) {
                hintCards.push(value, value);
            }

        }
        else if (cardTypeEnum == "CARD_AAA") {
            value = a3[3];
            while (value != -1 && value <= cardValue) {
                value = a2[value];
            }
            if (value != -1) {
                hintCards.push(value, value, value);
            }
        }
        else if (cardTypeEnum == "CARD_AAAB") {
            value = a3[3];
            while (value != -1 && value <= cardValue) {
                value = a2[value];
            }
            if(value != -1) {
                if(a3[1] > 0) {
                    hintCards.push(value, value, value, a3[1]);
                }
                else if(a3[2] > 0) {
                    hintCards.push(value, value, value, a3[2]);
                }
                else {
                    value = -1;  //找不到带的东西
                }
            }
            
        }
        else if (cardTypeEnum == "CARD_AAABB") {
            value = a3[3];
            while (value != -1 && value <= cardValue) {
                value = a2[value];
            }
            if (value != -1) {
                 if (a3[2] > 0) {
                    hintCards.push(value, value, value, a3[2], a3[2]);
                }
                else {
                    value = -1;  //找不到带的东西
                }
            }
        }
        else if (cardTypeEnum == "CARD_AAAA") {
            value = a3[4];
            while(value != -1 && value < cardValue) {
                value = a2[value];
            }
            if(value != -1) {
                hintCards.push(value, value, value, value);
            }
            else {
                if (a1[14] > 0 && a1[15] > 0) {
                    hintCards.push(14, 15);
                }
            }
        }
        else if (cardTypeEnum == "CARD_AAAABC") {
            value = a3[4];
            while (value != -1 && value < cardValue) {
                value = a2[value];
            }
            if(value != -1) {
                if(a3[1] != -1 && a2[a3[1]] != -1) {
                    hintCards.push(value, value, value, value, a3[1], a2[a3[1]]);
                }
                else if(a3[2] != -1) {
                    hintCards.push(value, value, value, value, a3[2], a3[2]);
                }
                else if(a3[3] != -1) {
                    hintCards.push(value, value, value, value, a3[3], a3[3]);
                }
                else {
                    value = -1;
                }
            }
        }
        else if (cardTypeEnum == "CARD_AAAABBCC") {
            value = a3[4];
            while (value != -1 && value < cardValue) {
                value = a2[value];
            }
            if(value != -1) {
                if(a3[2] != -1 && a2[a3[2]] != -1) {
                    hintCards.push(value, value, value, value, a3[2], a3[2], a2[a3[2]], a2[a3[2]]);
                }
                else if(a3[2] != -1 && a3[3] != -1) {
                    hintCards.push(value, value, value, value, a3[2], a3[2], a3[3], a3[3]);
                }
                else if(a3[3] != -1 && a2[a3[3]] != -1) {
                    hintCards.push(value, value, value, value, a3[3], a3[3], a2[a3[3]], a2[a3[3]]);
                }
                else {
                    value = -1;
                }
            }
        }
        else if (cardTypeEnum == "CARD_WZ") {
            
        }
        else if (cardTypeEnum == "CARD_ABCDE") {
            var dp = new Array(16);
            value == -1;
            dp[0] = 0;
            for(var i = 1; i <= 12 ; i++) {
                if(a1[i] > 0 && a1[i] < 4) {
                    dp[i] = dp[i-1] + 1;
                }
                else {
                    dp[i] = 0;
                }
            }
            for(var i = 1; i <= 12; i++) {
                if(dp[i] == cardLength && i - cardLength+1 > cardValue) {
                    value = i-cardLength+1;
                    for(var j = 0; j < cardLength; j++) {
                        hintCards.push(i-j);
                    }
                    break;
                }
            }
        }
        else if (cardTypeEnum == "CARD_AABBCC") {
            var dp = new Array(16);
            value == -1;
            dp[0] = 0;
            for (var i = 1; i <= 12; i++) {
                if (a1[i] > 1 && a1[i] < 4) {
                    dp[i] = dp[i - 1] + 1;
                }
                else {
                    dp[i] = 0;
                }
            }
            for (var i = 1; i <= 12; i++) {
                if (dp[i] == cardLength && i - cardLength + 1 > cardValue) {
                    value = i - cardLength + 1;
                    for (var j = 0; j < cardLength; j++) {
                        hintCards.push(i - j, i - j);
                    }
                    break;
                }
            }
        }
        else if (cardTypeEnum == "CARD_AAABBBCD") {
            var dp = new Array(16);
            value == -1;
            dp[0] = 0;
            for (var i = 1; i <= 15; i++) {
                if (a1[i] > 2 && a1[i] < 4) {
                    dp[i] = dp[i - 1] + 1;
                }
                else {
                    dp[i] = 0;
                }
            }
            for (var i = 1; i <= 15; i++) {
                if (dp[i] == cardLength && i - cardLength + 1 > cardValue) {
                    value = i - cardLength + 1;
                    for (var j = 0; j < cardLength; j++) {
                        hintCards.push(i - j, i - j, i - j);
                    }
                    break;
                }
            }
            var sonNum = cardLength;
            var tempArr = [];
            for (var i = 1; i <= 15; i++) {
                if (i < value || i > value + cardLength - 1) {
                    if(a1[i] > 0 && a1[i] < 4) {
                        for(var j = 0; j < a1[i]; j++) {
                            tempArr.push(i);
                            if(tempArr.length >= sonNum)
                                break;
                        }
                    }
                }
                if(tempArr.length >= sonNum)
                    break;
            }
            if(tempArr.length < sonNum) {
                value = -1;
                hintCards = [];
            }
            else {
                hintCards = hintCards.concat(tempArr);
            }
        }
        else if (cardTypeEnum == "CARD_AAABBBCCDD") {
            var dp = new Array(16);
            value == -1;
            dp[0] = 0;
            for (var i = 1; i <= 15; i++) {
                if (a1[i] > 2 && a1[i] < 4) {
                    dp[i] = dp[i - 1] + 1;
                }
                else {
                    dp[i] = 0;
                }
            }
            for (var i = 1; i <= 15; i++) {
                if (dp[i] == cardLength && i - cardLength + 1 > cardValue) {
                    value = i - cardLength + 1;
                    for (var j = 0; j < cardLength; j++) {
                        hintCards.push(i - j, i - j, i - j);
                    }
                    break;
                }
            }
            var sonNum = cardLength * 2;
            var tempArr = [];
            for (var i = 1; i <= 15; i++) {
                if (i < value || i > value + cardLength - 1) {
                    if (a1[i] > 1 && a1[i] < 4) {
                        tempArr.push(i, i);
                        if(tempArr.length >= sonNum)
                            break;
                    }
                }
            }
            if (tempArr.length < sonNum) {
                value = -1;
                hintCards = [];
            }
            else {
                hintCards = hintCards.concat(tempArr);
            }
        }
        else if (cardTypeEnum == "CARD_AAABBB") {
            var dp = new Array(16);
            value == -1;
            dp[0] = 0;
            for (var i = 1; i <= 15; i++) {
                if (a1[i] > 2 && a1[i] < 4) {
                    dp[i] = dp[i - 1] + 1;
                }
                else {
                    dp[i] = 0;
                }
            }
            for (var i = 1; i <= 15; i++) {
                if (dp[i] == cardLength && i - cardLength + 1 > cardValue) {
                    value = i - cardLength + 1;
                    for (var j = 0; j < cardLength; j++) {
                        hintCards.push(i - j, i - j, i - j);
                    }
                    break;
                }
            }

        }
        else if (cardTypeEnum == "CARD_ARBITRARY") {
            for(var i = 1; i <= 13; i++) {
                if(a1[i] > 0 && a1[i] != 4) {
                    for(var j = 1; j <= a1[i]; j++) {
                        hintCards.push(i);
                    }
                    value = i;
                    if(a1[i] == 3) {
                        if(a3[1] > 0 && a3[2] > 0) {
                            if(a3[1] < a3[2]) {
                                hintCards.push(a3[1]);
                            }
                            else {
                                hintCards.push(a3[2], a3[2]);
                            }
                        }
                        else if(a3[1] > 0) {
                            hintCards.push(a3[1]);
                        }
                        else if(a3[2] > 0) {
                            hintCards.push(a3[2], a3[2]);
                        }
                    }
                    break;
                }
            }
            if(hintCards.length == 0) {
                value = -1;
            }
        }
        

        if (value == -1 && cardTypeEnum != "CARD_AAAA" && cardTypeEnum != "CARD_WZ") {
            if (a3[4] != -1) {
                hintCards.push(a3[4], a3[4], a3[4], a3[4]);
            }
            else if (a1[14] > 0 && a1[15] > 0) {
                hintCards.push(14, 15);
            }
        }
        console.log(hintCards);
        this.chooseHintCards(hintCards);


    },

    chooseHintCards : function(hintCard) {
        if(hintCard.length == 0) {
            return;
        }
        var choosedCard = [];
        var upcomingCards = [];
        var j = 0;
        hintCard.sort((a, b)=> {return a - b;});
        for(var i = this.cardValues.length-1; i >= 0 && j < hintCard.length; i--) {
            if(this.cardValues[i] == hintCard[j]) {
                choosedCard.push(i);
                upcomingCards.push(this.cardNum - 1 - i);
                j++;
            }
        }
        console.log(choosedCard);
        this.choosedCard = choosedCard;
        this.upcomingCards = upcomingCards;
        for(var i in this.cardInstance) {
            this.cardInstance[i].getComponent("card").notChoose2();
        }
        for(var i in choosedCard) {
            this.cardInstance[choosedCard[i]].getComponent("card").choose();
        }
        this.judgeCard();
    },

    re_inputNickName: function (text, editbox) {
        this.re_nickName = text;
    },

    re_inputPassword : function(text, editbox) {
        this.re_passWord = text;
    },

    re_inputPassword2: function(text, editbox) {
        this.re_passWord2 = text;
    },

    lo_inputNickName: function(text, editbox) {
        this.lo_nickName = text;
    },

    lo_inputPassword : function(text, editbox) {
        this.lo_password = text;
    },

    login : function() {
        var err = this.node.getChildByName("login").getChildByName("errtext");
        if(this.lo_nickName == undefined || this.lo_nickName.length == 0) {
            err.active = true;
            err.getComponent(cc.Label).string = "用户名不能为空";
            setTimeout(() => { err.active = false }, 2000);
            return;
        }
        else if(this.lo_password == undefined) {
            err.active = true;
            err.getComponent(cc.Label).string = "密码不能为空";
            setTimeout(() => { err.active = false }, 2000);
            return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open("POST", domainName + "user/login");
        xhr.setRequestHeader("Content-Type", "application/json");
        var that = this;
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if(JSON.parse(xhr.response).code == 0) {
                    console.log(xhr.response);
                    that.node.getChildByName("login").active = false;
                    that.node.getChildByName("beginMenu").active = true;
                    that.showToast("登录成功！");
                    that.token = JSON.parse(xhr.response).data;
                }
                else {
                    err.active = true;
                    err.getComponent(cc.Label).string = JSON.parse(xhr.response).data;
                    setTimeout(() => { err.active = false }, 2000);
                }
            }
        }
        var data = {
            username : this.lo_nickName,
            password : this.lo_password,
        };
        xhr.send(JSON.stringify(data));

    },

    gotoRegister : function() {
        this.node.getChildByName("login").active = false;
        this.node.getChildByName("register").active = true;
    },

    returntoLogin : function() {
        this.node.getChildByName("login").active =true;
        this.node.getChildByName("register").active = false;
    },

    register : function() {
        var err = this.node.getChildByName("register").getChildByName("errtext");
        if(this.re_nickName == undefined) {
            err.active = true;
            err.getComponent(cc.Label).string = "用户名不能为空";
            setTimeout(()=>{err.active = false}, 2000);
            return;
        }
        if(this.re_passWord == undefined || this.re_passWord.length == 0) {
            err.active = true;
            err.getComponent(cc.Label).string = "密码不能为空";
            setTimeout(() => { err.active = false }, 2000);
            return;
        }
        if(this.re_passWord2 == undefined || this.re_passWord2.length == 0) {
            err.active = true;
            err.getComponent(cc.Label).string = "确认密码不能为空";
            setTimeout(() => { err.active = false }, 2000);
            return;
        }
        if(this.re_passWord != this.re_passWord2) {
            err.active = true;
            err.getComponent(cc.Label).string = "两次密码不一致";
            setTimeout(() => { err.active = false }, 2000);
            return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open("POST", domainName + "user/register");
        xhr.setRequestHeader("Content-Type", "application/json");
        var that = this;
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if(JSON.parse(xhr.response).code == 0) {
                    that.node.getChildByName("register").active = false;
                    that.node.getChildByName("login").active = true;
                    that.showToast("注册成功！");
                }   
                else {
                    err.active = true;
                    err.getComponent(cc.Label).string = JSON.parse(xhr.response).data;
                    setTimeout(() => { err.active = false }, 2000);
                }
            }
        }
        var data = {
            username: this.re_nickName,
            password: this.re_passWord,
        };
        xhr.send(JSON.stringify(data));

    }
    ,
    showToast : function(string) {
        var toast = this.node.getChildByName("toast");
        toast.active = true;
        toast.getChildByName("text").getComponent(cc.Label).string = string;
        setTimeout(() => { toast.active = false }, 2000);
    }


});
